/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beanController;

import com.matrimonysite.entity.Role;
import com.matrimonysite.entity.Users;
import com.matrimonysite.sessionbean.UsersFacade;
import java.io.IOException;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author khanhnguyen
 */
@ManagedBean(name="Login")
@SessionScoped
public class Login {
    @EJB
    private UsersFacade userFacade;
    private Users user;

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }
    
    /**
     * Creates a new instance of Login
     */
    public Login() {
        user = new Users();
        userFacade = new UsersFacade();
    }
    
    public String doLogin(){
        String result = "login failed";
        String username = user.getUsername();
        String password = user.getPassword();
        Users user1 = userFacade.getUserName(username);
        if (user1 != null) {            
            if (user1.getPassword().equals(password)) {
                FacesContext context = FacesContext.getCurrentInstance();
                HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
                session.setAttribute("user", username);                

                Role role= user1.getRoleID();                                
                session.setAttribute("role", role);
                
                result="Login succesful";
            } else {
                FacesContext face = FacesContext.getCurrentInstance();
                face.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Password incorect", "<span>Please input Password</span>"));
                result = "Password incorrect";
            }
        } else {
            FacesContext face = FacesContext.getCurrentInstance();
            face.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username incorect", "<span>Please input User Name</span>"));
            result = "Username incorrect";
        }
        return result;
    }
    public void doLogout() throws IOException{
        FacesContext faces = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) faces.getExternalContext().getSession(false);
        session.removeAttribute("user");
        session.removeAttribute("role");
        
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.sendRedirect("../faces/login.xhtml");
    }
}
